package cn.chendd.example.jpa.nativequery;

import org.hibernate.query.ParameterMetadata;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;

import java.util.List;

/**
 * @author chendd
 * @date 2020/5/6
 */
public class SQLQueryMap extends SQLQuery {

    @Override
    public Object execute(SqlParameter sqlParameter) {
        NativeQueryImpl nativeQuery = super.getEntityManager().createNativeQuery(sqlParameter.getSql()).unwrap(NativeQueryImpl.class);
        List<Object> paramList = sqlParameter.getParamList();
        ParameterMetadata pmd = nativeQuery.getParameterMetadata();
        int parameterCount = pmd.getParameterCount();
        for(int i=0 ; i < parameterCount; i++){
            nativeQuery.setParameter(i + 1 , paramList.get(i));
        }
        nativeQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return super.queryResult(nativeQuery);
    }

}